package com.ego.order.config;

import com.ego.order.properties.PayProperties;
import com.github.wxpay.sdk.IWXPayDomain;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Slf4j
@Configuration
@EnableConfigurationProperties(PayProperties.class)
public class WXPayConfiguration extends WXPayConfig {

    @Resource
    private PayProperties payProperties;

    private byte[] certData;

    @Bean
    public WXPay wxPay() {
        WXPay result= null;
        try {
            result= new WXPay(this);
        } catch (Exception e) {
            log.error("初始化WxPay错误", e);
        }
        return result;
    }

    @Override
    public IWXPayDomain getWXPayDomain() {
        return new IWXPayDomain() {
            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }

            @Override
            public DomainInfo getDomain(WXPayConfig config) {
                return new DomainInfo("api.mch.weixin.qq.com",true);
            }
        };
    }

    @Override
    public String getAppID() {
        return payProperties.getAppID();
    }

    @Override
    public String getMchID() {
        return payProperties.getMchID();
    }

    @Override
    public String getKey() {
        return payProperties.getKey();
    }

    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return payProperties.getHttpConnectTimeoutMs();
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return payProperties.getHttpReadTimeoutMs();
    }
}
